<?php

class CommentModel extends SCModel {
	
	public function __construct() {
		parent::__construct();
	}
	
	/**
	 * 
	 * 获取回应数据
	 * @param integer $thing_id
	 * @return array
	 */
	public function getComments($thing_id, $type = 'thing') {
		$comments = $this->from('comment')->where('related_id = '.$thing_id.' AND type = '.ThingModel::$_thingType[$type])->orderBy('id DESC')->find();
		return $this->assemblingComments($comments);
	}
	
	/**
	 * 
	 * 获取回应数据
	 * @param integer $id
	 * @return object
	 */
	public function getComment($id) {
		$comment = $this->from('comment')->where('id = '.$id)->limit(1)->find();
		$comment->post_date = CommonFunction::friendlyTime($comment->post_date);
		$userModel = new UserModel();
		$comment->user = $userModel->getBasicInfo($comment->user_id);
		if($comment->reply_id) {
			$reply_ids = explode(',', $comment->reply_id);
			$comment->replyer = array();
			foreach($reply_ids as $reply_id) {
				array_push($comment->replyer, $userModel->getBasicInfo($reply_id));
			}
		}
		return $comment;
	}
	
	/**
	 * 
	 * 获取回应数
	 * @param unknown_type $thingId
	 */
	public function getCommentCount($thingId, $type = 'thing') {
		return count($this->from('comment')->field('id')->where('related_id = '.$thingId.' AND type = '.ThingModel::$_thingType[$type])->find());
	}
	
	/**
	 * 
	 * 组装其他信息到数据流中
	 * @param array $comments
	 * @return array
	 */
	protected function assemblingComments(array $comments) {
		$userModel = new UserModel();
		foreach($comments as $key=>$comment) {
			$comments[$key]->post_date = CommonFunction::friendlyTime($comment->post_date);
			$comments[$key]->user = $userModel->getBasicInfo($comment->user_id);
			if($comment->reply_id) {
				$reply_ids = explode(',', $comment->reply_id);
				$comments[$key]->replyer = array();
				foreach($reply_ids as $reply_id) {
					array_push($comments[$key]->replyer, $userModel->getBasicInfo($reply_id));
				}
			}
		}
		return $comments;
	}
} 